package com.hwg.emp.service.impl;

import java.util.List;

import com.hwg.emp.common.exception.EmpException;
import com.hwg.emp.common.util.DBUtil;
import com.hwg.emp.dao.DaoFactory;
import com.hwg.emp.dao.DeptDAO;
import com.hwg.emp.dao.EmployeeDAO;
import com.hwg.emp.dto.EmpDTO;
import com.hwg.emp.dto.PageBean;
import com.hwg.emp.model.EmployeeMD;
import com.hwg.emp.service.EmployeeService;

public class EmployeeServiceImpl implements EmployeeService{
	private EmployeeDAO dao=DaoFactory.getDao(EmployeeDAO.class);
	private DeptDAO deptDAO = DaoFactory.getDao(DeptDAO.class);
	
	@Override
	public EmpDTO selectOwnInfoById(String id) throws Exception {
		return dao.selectOwnInfoById(id);
	}
	
	@Override
	public void insertEmployee(EmployeeMD t) throws Exception {
		DBUtil.beginTranscation();
		int i = dao.insert(t);
		if (i>0) {
			deptDAO.updateMembersPlusOne(t.getDept());
			DBUtil.commitTranscation();
		}else {
			DBUtil.rollbackTranscation();
		}
	}

	@Override
	public String selectEmployeeDeptId(String userId) throws Exception {
		// TODO Auto-generated method stub
		return dao.selectEmployeeDeptId(userId);
	}


	@Override
	public int selectEmployeesAcount( String dept_id) throws Exception {
		// TODO Auto-generated method stub
		return dao.selectEmployeesAcount( dept_id);
	}

	@Override
	public List selectEmployees(String dept_id, PageBean pagebean)
			throws Exception {
		// TODO Auto-generated method stub
		return dao.selectEmployees( dept_id,pagebean);
	}

	@Override
	public boolean deleteEmpsByIds(String... ids) throws Exception {
		// TODO Auto-generated method stub
		DBUtil.beginTranscation();
		int count = 0;
		for (String id : ids) {
			EmployeeMD e = dao.select("id", id);
			deptDAO.updateMembersMinusOne(deptDAO.select("id", e.getDept().getId()));
			count += dao.delete("id", id);
		}
		if(count==ids.length){
			DBUtil.commitTranscation();
			return true;
		}else{
			DBUtil.rollbackTranscation();
			return false;
		}
	}

	@Override
	public void update(EmployeeMD t) throws Exception {
		// TODO Auto-generated method stub
		DBUtil.beginTranscation();
		int i = dao.update(t);
		if (i>0) {
			DBUtil.commitTranscation();
		}else {
			DBUtil.rollbackTranscation();
		}
	}

	@Override
	public List selectEmpsByCondition(String phone, PageBean pagebean) throws Exception {
		// TODO Auto-generated method stub
		return dao.selectEmpsByCondition(phone,pagebean);
	}

	@Override
	public int selectEmpsCountByCondition(String phone) throws Exception {
		// TODO Auto-generated method stub
		return dao.selectEmpsCountByCondition(phone);
	}
}
